import * as React from 'react';
// TODO: 为何不能用 BrowserRouter
import { HashRouter as Router, Switch, Route } from 'react-router-dom';

import { Navbar, NavbarLink, NavbarItem } from './components/navbar';
import { Button } from './components/button';

import routes from './routes';

import { Subscription } from 'rxjs';
import { User } from './models/user';

import authService from './services/svc.auth';

interface AppState {
  authenticated: boolean;
  user: User | undefined;
  loading: boolean;
}

export default class App extends React.Component {
  private subjects: Subscription | undefined;

  state: AppState = {
    authenticated: false,
    user: undefined,
    loading: false,
  };

  componentDidMount() {
    this.subjects = authService.user.subscribe(({ authenticated, user }) => {
      this.setState({ authenticated, user });
    });
    this.setState({ loading: true });
    authService
      .load()
      .then(() => this.setState({ loading: false }))
      .catch((err) => {
        console.error(err);
        this.setState({ loading: false });
      });
  }

  componentWillUnmount() {
    this.subjects!.unsubscribe();
  }

  render() {
    const { authenticated, user } = this.state;

    return (
      <Router>
        <Navbar>
          <NavbarLink to="/">Home</NavbarLink>
          <NavbarLink to="/about">About</NavbarLink>
          <NavbarLink to="/about/comps">组件</NavbarLink>
          <NavbarLink to="/users">Users</NavbarLink>
          <NavbarLink to="/workspace">Workspace</NavbarLink>
          {authenticated || <NavbarLink to="/user/login">登录</NavbarLink>}
          {authenticated && <NavbarItem>{user.nickName || user.username}</NavbarItem>}
          {authenticated && <NavbarLink to="/post/new">写文章</NavbarLink>}
          {authenticated && (
            <NavbarItem>
              <Button onClick={() => authService.logout()}>退出</Button>
            </NavbarItem>
          )}
        </Navbar>
        <div>
          {/* A <Switch> looks through its children <Route>s and
              renders the first one that matches the current URL. */}
          <Switch>
            {routes.map((route, index) => (
              <Route path={route.path} key={index} children={<route.page />} />
            ))}
          </Switch>
        </div>
      </Router>
    );
  }
}
